package com.wjb.controller;

import com.wjb.common.BaseResultString;
import com.wjb.config.QuartzConfig;
import com.wjb.feign.CouponClient;
import com.wjb.feign.ItemStockClient;
import com.wjb.feign.OrderServiceFeign;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

/**
 * @author : 王济彬
 * @date: 2025/5/24 - 05 - 24 - 11:28
 * @Description: com.wjb.controller
 * @version: 1.0
 */
@RestController
@RequestMapping("/placeOrder")
public class PlaceOrderController {

    private static final Logger log =  LoggerFactory.getLogger(PlaceOrderController.class);

    @Resource
    private ItemStockClient itemStockClient;

    @Resource
    private OrderServiceFeign orderServiceFeign;

    @Resource
    private CouponClient couponClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private QuartzConfig quartzConfig;

    @RequestMapping("/provide")
    public String placeOrder(int id,int isUseCoupon) throws Exception {
        CompletableFuture job1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("正在启动下单");
            if (!BaseResultString.STOCK_SUCCESS.equals(itemStockClient.testCreateOrder())) {
                return "没有商品,订单创建失败";
            }
            System.out.println("库存扣减成功，执行下一步");

            //创建订单操作且扣除库存

            // 调用优惠卷操作，预扣优惠卷


            //调用用户积分操作，预扣积分

            //通知商家下单


            return "下单成功";
        }).exceptionally(ex -> {
            log.error("Error: {}" + ex.getMessage());
            return "下单失败";
        });

        CompletableFuture job2 = CompletableFuture.runAsync(() -> {
            System.out.println("启动定时执行任务");
            SchedulerFactory factory = null;
            try{
                factory = new StdSchedulerFactory();
                Scheduler scheduler = factory.getScheduler();
                scheduler.scheduleJob(quartzConfig.createJobDetail(), quartzConfig.getTrigger());
                scheduler.start();
            }catch (Exception e){
                e.printStackTrace();
            }
        });

        return (String)job1.join();
    }
}

    /**
     * 延迟交换机发送消息
     * @throws IOException
     */
//    public void publishWithConfirm() throws IOException {
//        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {   //保证消息到达交换机
//            @Override
//            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
//                if (ack) {
//                    System.out.println("消息发送至交换机");
//                } else {
//                    System.out.println("消息发送失败");
//                }
//            }
//        });
//        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {   //保证消息到达队列
//
//            @Override
//            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
//                System.out.println("消息发送至队列失败");
//            }
//        });
//        rabbitTemplate.convertAndSend(OrderExchangeConfig.ORDER_EXCHANGE, OrderExchangeConfig.ORDER_ROUTING_KEY, "create order", new MessagePostProcessor() {
//            @Override
//            public Message postProcessMessage(Message message) throws AmqpException {
//                String uuid = UUID.randomUUID().toString();
//                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);  //持久化消息
//                message.getMessageProperties().setCorrelationId(uuid);
//                return message;
//            }
//        });
//        System.out.println("消息发送成功");
//        System.in.read();
//    }

    /**
     * 优惠卷使用队列
     */
//    public void publishCouponUse() throws IOException {
//        rabbitTemplate.convertAndSend(CouponExchangeConfig.CPUPON_EXCHANGE, CouponExchangeConfig.CPUPON_ROUTING_KEY, "use_coupon", new MessagePostProcessor() {
//
//            @Override
//            public Message postProcessMessage(Message message) throws AmqpException {
//                String uuid = UUID.randomUUID().toString();
//                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
//                message.getMessageProperties().setCorrelationId(uuid);
//                return message;
//            }
//        });
//    }

